package com.kbbywyclient.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.kbbywyclient.R;
import com.kbbywyclient.app.Constants;
import com.kbbywyclient.callback.RecyclerItemClickedListener;
import com.kbbywyclient.data.entity.MinePartnerData;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.MinePartnerModule;
import com.kbbywyclient.presenter.MinePartnerPresenter;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.adapter.MinePartnerSummaryAdapter;
import com.kbbywyclient.ui.contarct.MinePartnerContract;
import com.kbbywyclient.ui.pop.PureListPop;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.StringUtil;
import com.kbbywyclient.widget.CustomToolBar;
import com.kbbywyclient.widget.divider.VerticalItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

/**
 * Created by Jiangzx on 2017/10/30 10:37.
 */

public class MinePartnerActivity extends BaseActivity implements MinePartnerContract.View{
    @BindView(R.id.v_toolbar)
    CustomToolBar toolBar;
    @BindView(R.id.app_bar)
    AppBarLayout appBarLayout;
    @BindView(R.id.tv_partner_summary_left_bottom)
    TextView tvLeftBottom;
    @BindView(R.id.tv_partner_summary_center_top)
    TextView tvCenterTop;
    @BindView(R.id.tv_partner_summary_center_bottom)
    TextView tvCenterBottom;
    @BindView(R.id.ll_partner_summary_right)
    LinearLayout llRight;
    @BindView(R.id.tv_partner_summary_right_top)
    TextView tvRightTop;
    @BindView(R.id.tv_partner_summary_right_bottom)
    TextView tvRightBottom;

    @BindView(R.id.et_content_search)
    EditText etContentSearch;//搜索输入框
    @BindView(R.id.iv_clear)
    ImageView ivClear;//清除搜索框内容按钮
    @BindView(R.id.ll_level)
    LinearLayout llLevel;
    @BindView(R.id.tv_level)
    TextView tvLevel;//级别
    @BindView(R.id.ll_city)
    LinearLayout llCity;
    @BindView(R.id.tv_city)
    TextView tvCity;//城市

    @BindView(R.id.sr_layout)
    SmartRefreshLayout srLayout;
    @BindView(R.id.recycle_view)
    RecyclerView recyclerView;

    @Inject
    MinePartnerPresenter presenter;

    private MinePartnerData.Header.Role selectedRole;
    private List<MinePartnerData.Header.Role> levels;
    private PureListPop<MinePartnerData.Header.Role> levelPop;

    private MinePartnerData.Header.City selectedCity;
    private List<MinePartnerData.Header.City> cities;
    private PureListPop<MinePartnerData.Header.City> cityPop;

    private MinePartnerSummaryAdapter adapter;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_mine_partner;
    }

    @Override
    protected void initView() {
        ImmersionBar.with(this).
                keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN |
                        WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN).
                init();
        toolBar.setLeftViewOnClickLinster(v -> finish());

        switch (getUser().getRole()){
            case Constants.LEVEL_DISTRIBUTOR:
                //总代理
                tvCenterTop.setText(R.string.text_month_application);
                tvRightTop.setText(R.string.text_month_settlement);
                break;
            case Constants.LEVEL_FIRST:
            case Constants.LEVEL_SECOND:
                tvCenterTop.setText(R.string.text_month_settlement);
                tvRightTop.setText(R.string.text_month_mine_reward);

                llLevel.setVisibility(View.GONE);
                break;
            default:
                llRight.setVisibility(View.GONE);
                tvCenterTop.setText(R.string.text_month_settlement);

                llLevel.setVisibility(View.GONE);
                break;
        }

        final LinearLayoutManager layoutManager = new LinearLayoutManager(MinePartnerActivity.this,
                LinearLayoutManager.VERTICAL,
                false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new VerticalItemDecoration(0XFFDDDDDD, 1));
        srLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                presenter.page++;
                loadList();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                presenter.clearListData();
                clearListUi();
                loadList();
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (layoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
                        appBarLayout.setExpanded(true, true);
                    }
                }
            }
        });
    }


    private void loadList(){
        presenter.loadList(getUser().getSalesID(),
                etContentSearch.getText().toString().trim(),
                selectedCity==null?0:Integer.parseInt(selectedCity.getCityId()),
                selectedRole==null?0:selectedRole.getRole(),
                presenter.page);
    }

    @Override
    public void initData() {
        tvLeftBottom.setText(R.string.text_default_txt_value);
        tvCenterBottom.setText(R.string.text_default_txt_value);
        tvRightBottom.setText(R.string.text_default_txt_value);

        int salesId=getUser().getSalesID();
        presenter.loadHeader(salesId);
        loadList();
    }

    @Override
    public void initAppComponent(AppComponent appComponent) {
        appComponent.getMinePartnerComponent(new MinePartnerModule(this)).inject(this);
    }

    @OnClick({R.id.fr_partner_summary, R.id.iv_clear, R.id.ll_level, R.id.ll_city, R.id.iv_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fr_partner_summary:
                //合伙人统计明细
                ActivitySkipUtil.skipAnotherActivity(MinePartnerActivity.this,
                        MinePartnerDetailsActivity.class);
                break;
            case R.id.iv_clear:
                etContentSearch.setText("");
                break;
            case R.id.ll_level:
                //选择级别
                dismissCityPop();
                showLevelPop();
                break;
            case R.id.ll_city:
                //选择城市
                dismissLevelPop();
                showCityPop();
                break;
            case R.id.iv_search:
                //搜索
                srLayout.autoRefresh();
                break;
        }
    }


    private void showLevelPop() {
        if(levels!=null&&levels.size()>0){
            final Context context = MinePartnerActivity.this;
            if (levelPop == null) {
                RecyclerItemClickedListener<MinePartnerData.Header.Role> listener = r -> {
                    levelPop.dismiss();
                    selectedRole=r;
                    tvLevel.setText(selectedRole.getRoleName());
                };
                levelPop = new PureListPop<>(context, levels, listener);
                levelPop.setWidth(llLevel.getWidth());
                levelPop.setOnDismissListener(() -> {
                    tvLevel.setCompoundDrawablesWithIntrinsicBounds(null,
                            null,
                            ContextCompat.getDrawable(context, R.mipmap.icon_green_arrow_down),
                            null);
                });
            }
            if (!levelPop.isShowing()) {
                int[] position = new int[2];
                llLevel.getLocationOnScreen(position);
                tvLevel.setCompoundDrawablesWithIntrinsicBounds(null,
                        null,
                        ContextCompat.getDrawable(context, R.mipmap.icon_green_arrow_up),
                        null);
                levelPop.showAtLocation(llLevel, Gravity.NO_GRAVITY, position[0], position[1] + llLevel.getHeight());
            }
        }
    }

    private void dismissLevelPop() {
        if (levelPop != null) {
            levelPop.dismiss();
        }
    }

    private void showCityPop() {
        if(cities!=null&&cities.size()>0){
            final Context context = MinePartnerActivity.this;
            if (cityPop == null) {
                RecyclerItemClickedListener<MinePartnerData.Header.City> listener = city -> {
                    cityPop.dismiss();
                    selectedCity=city;
                    tvCity.setText(city.getCityName());
                };
                cityPop = new PureListPop<>(context, cities, listener);
                cityPop.setWidth(StringUtil.dip2px(90));
                cityPop.setOnDismissListener(() -> {
                    tvCity.setCompoundDrawablesWithIntrinsicBounds(null,
                            null,
                            ContextCompat.getDrawable(context, R.mipmap.icon_green_arrow_down),
                            null);
                });
            }
            if (!cityPop.isShowing()) {
                int[] position = new int[2];
                llCity.getLocationOnScreen(position);
                tvCity.setCompoundDrawablesWithIntrinsicBounds(null,
                        null,
                        ContextCompat.getDrawable(context, R.mipmap.icon_green_arrow_up),
                        null);
                cityPop.showAtLocation(llCity, Gravity.NO_GRAVITY, position[0], position[1] + llCity.getHeight());
            }
        }
    }

    private void dismissCityPop() {
        if (cityPop != null) {
            cityPop.dismiss();
        }
    }

    @OnTextChanged(R.id.et_content_search)
    public void afterTextChange(Editable s) {
        if (s.length() > 0) {
            ivClear.setVisibility(View.VISIBLE);
        } else {
            ivClear.setVisibility(View.GONE);
        }
    }

    @Override
    public void onHeaderSuccess(MinePartnerData.Header header) {
        levels=header.getRoles();
        cities=header.getCitys();
        int role = getUser().getRole();
        switch (role) {
            case Constants.LEVEL_DISTRIBUTOR:
                //总代理
                tvLeftBottom.setText(header.getParam1());
                tvCenterBottom.setText(header.getParam2());
                tvRightBottom.setText(header.getParam3());
                break;
            case Constants.LEVEL_FIRST:
            case Constants.LEVEL_SECOND:
                //一级、二级合伙人
                tvLeftBottom.setText(header.getParam1());
                tvCenterBottom.setText(header.getParam2());
                tvRightBottom.setText(String.format(Locale.CHINESE,Constants.AMOUNT_FORMAT,Double.parseDouble(header.getParam3())));
                break;
            default:
                //普通合伙人
                tvLeftBottom.setText(header.getParam1());
                tvCenterBottom.setText(header.getParam2());
                break;
        }
    }

    @Override
    public void clearListUi() {
        presenter.clearListData();
        if(adapter!=null){
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void completeLoadContent(boolean canLoadMore, List<MinePartnerData.Content.Partner> partners) {
        if(adapter==null){
            adapter=new MinePartnerSummaryAdapter(getUser().getRole(),partners);
            adapter.setItemClickedListener((action, partner) -> {
                if(action==MinePartnerSummaryAdapter.ItemClickListener.ACTION_VIEW_DETAIL){
                    HashMap<String,Object> params=new HashMap<>();
                    params.put(ClerkDetailsActivity.CLERK_LOGO_S,
                            partner.getLogo());
                    params.put(ClerkDetailsActivity.CLERK_ID_I,
                            partner.getSaleID());
                    params.put(ClerkDetailsActivity.CLERK_NAME_S,
                            partner.getTrueName());
                    params.put(ClerkDetailsActivity.CLERK_MOBILE_S,
                            partner.getMobile());
                    ActivitySkipUtil.skipAnotherActivity(MinePartnerActivity.this,
                            ClerkDetailsActivity.class,params);

                } else if(action==MinePartnerSummaryAdapter.ItemClickListener.ACTION_CALL){
                    //打电话
                    Intent intent=new Intent(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse("tel:"+partner.getMobile()));
                    if(getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY)!=null){
                        startActivity(intent);
                    }
                }
            });
        }
        if(recyclerView.getAdapter()==null){
            recyclerView.setAdapter(adapter);
        }else{
            adapter.notifyDataSetChanged();
        }
        srLayout.finishRefresh();
        srLayout.finishLoadmore();
        if(canLoadMore){
            srLayout.setLoadmoreFinished(false);
        }else{
            srLayout.setLoadmoreFinished(true);
        }
    }
}
